package com.sj.uabrowser.mvp.main.view.act;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.just.agentweb.AgentWeb;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.Constant;
import com.sj.uabrowser.app.SPUtil;
import com.sj.uabrowser.app.StatusBarUtil;
import com.sj.uabrowser.app.Util;
import com.sj.uabrowser.db.CollectHistory;
import com.sj.uabrowser.db.gen.CollectHistoryDao;
import com.sj.uabrowser.framework.BaseActivity;
import com.sj.uabrowser.framework.BasePresenter;
import com.sj.uabrowser.mvp.main.bean.News;
import com.sj.uabrowser.mvp.share.ResourcesManager;
import com.sj.uabrowser.mvp.share.tencent.qq.QQShare;
import com.sj.uabrowser.mvp.share.tencent.qzone.QQZoneShare;
import com.sj.uabrowser.mvp.share.wechat.friends.WechatShare;
import com.sj.uabrowser.mvp.share.wechat.moments.WechatMomentsShare;
import com.sj.uabrowser.net.AuthResultClient;
import com.sj.uabrowser.net.ServiceApi;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewsDetailAct extends BaseActivity implements CompoundButton.OnCheckedChangeListener, PlatformActionListener {

    FrameLayout mViewParent;
    @BindView(R.id.cb_shoucang)
    CheckBox cbShoucang;
    private AgentWeb mAgentWeb;
    View tvClose;
    private String url;
    private CollectHistory bean;
    private CollectHistoryDao collectHistoryDao;

    private void loadSearchPage(String url) {
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mViewParent, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(webViewClient)
                .createAgentWeb()
                .ready()
                .go(url);
        WebView webView = mAgentWeb.getWebCreator().getWebView();
//        WebView初始化之后需要添加如下代码开启Cookie：
        if (Build.VERSION.SDK_INT >= 21) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        } else {
            CookieManager.getInstance().setAcceptCookie(true);
        }
        WebSettings webSettings = webView.getSettings();
        int fontSize = SPUtil.get(this, SPUtil.KEY_FONTSIZE, Constant.FONTSIZE_NORMAL);
        webSettings.setDefaultFontSize(fontSize);
        webSettings.setSupportZoom(true);
        //支持javascript
        webSettings.setJavaScriptEnabled(true);
// 设置可以支持缩放
        webSettings.setSupportZoom(true);
// 设置出现缩放工具
        webSettings.setBuiltInZoomControls(true);
//扩大比例的缩放
        webSettings.setUseWideViewPort(true);
//自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webSettings.setLoadWithOverviewMode(true);
//        webView.setDownloadListener(new DownloadListener() {
//            @Override
//            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                Intent intentUrl = new Intent(BrowserActivity.this, SearchAct.class);
//                intentUrl.putExtra("httpurl", url);
//                startActivity(intentUrl);
//                finish();
//            }
//        });
    }

    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();
            String uriOverride = uri.toString();
            Log.e("uriOverride:", uriOverride);
            if (uriOverride.startsWith("baiduboxlite://")
                    || uriOverride.startsWith("baiduboxapp://")
                    || uriOverride.startsWith("iqiyi://")
                    || uriOverride.startsWith("https://mo.baidu.com/boxandroid")
                    || uriOverride.startsWith("tbopen://")

            ) {
                return true;
            }
            return false;
        }


        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();


            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mAgentWeb != null) {
                mAgentWeb.getIndicatorController().setProgress(100);
            }
        }
    };

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mAgentWeb.getWebCreator().getWebView().canGoBack()) {
            mAgentWeb.getWebCreator().getWebView().goBack();
        } else
            super.onBackPressed();
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_news_detail;
    }

    @Override
    public void setView() {
        StatusBarUtil.setTransparentForImageView(this, null);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.news_text_selected), 0);
        mViewParent = findViewById(R.id.viewParent);
        resManager = ResourcesManager.getInstace(this);
        tvClose = findViewById(R.id.tv_close);
        tvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        News news = (News) getIntent().getSerializableExtra("news");
        if(news!=null) {
            url = news.getClk_url();
            if(!noTrace) {
                collectHistoryDao = daoSession.getCollectHistoryDao();
                List<CollectHistory> histories = collectHistoryDao.queryRaw("where url = ?", new String[]{url});
                if (histories.size() == 0) {
                    bean = new CollectHistory();
                    bean.setUrl(news.getClk_url());
                    bean.setDate(new Date().getTime());
                    bean.setType(CollectHistory.TYPE_NEWS);
                    bean.setTitle(news.getTitle());
                    bean.setIsHis(true);
                    collectHistoryDao.insert(bean);
                } else {
                    bean = histories.get(0);
                    bean.setDate(new Date().getTime());
                    collectHistoryDao.update(bean);
                }
            }
            List<String> list = news.getImp_tracking();
            if(list!=null&&list.size()>0) {
                String imp = getIntent().getStringExtra("imp");

                if (!TextUtils.isEmpty(imp)) {
                    AuthResultClient.getService(ServiceApi.class).rcd(imp).enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                }
            }
            loadSearchPage(url);
            cbShoucang.setOnCheckedChangeListener(this);
        }else finish();
    }

    @Override
    public void setData() {

    }

    @OnClick({R.id.iv_pre, R.id.iv_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_pre:
                onBackPressed();
                break;
            case R.id.iv_share:
                showShare();
                setShareListener(webShareListener);
                break;
        }
    }

    private ResourcesManager resManager;
    private View.OnClickListener webShareListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            resManager.setTitle(getResources().getString(R.string.app_name));
            resManager.setText("一款简单好用的浏览器");
            if(bean!=null){
//                resManager.setTitle(getResources().getString(R.string.app_name));
                resManager.setText(bean.getTitle());
            }
            resManager.setUrl(url);
            resManager.setTitleUrl(url);
            switch (v.getId()) {
                case R.id.rl_wechat:
                    WechatShare wechatShare = new WechatShare(NewsDetailAct.this);
                    wechatShare.shareWebpager();
                    break;
                case R.id.rl_friends:
                    WechatMomentsShare wechatMomentsShare = new WechatMomentsShare(NewsDetailAct.this);
                    wechatMomentsShare.shareWebpager();
                    break;
                case R.id.rl_qq:
                    QQShare qqShare = new QQShare(NewsDetailAct.this);
                    qqShare.shareWebPager();
                    break;
                case R.id.rl_qqzone:
                    QQZoneShare qqZoneShare = new QQZoneShare(NewsDetailAct.this);
                    qqZoneShare.shareWebPager();
                    break;
            }
            if(popupWindowShared!=null)popupWindowShared.dismiss();
        }
    };


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            buttonView.setEnabled(false);
            showToast("收藏成功！");
            //插入数据库中
            if(bean!=null){
                bean.setIsLike(true);
                if(collectHistoryDao!=null)collectHistoryDao.update(bean);
            }else{
                showToast("请到菜单-收藏列表中删除收藏记录！");
            }
        }
    }


    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Util.showToastShort("分享成功!");
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Util.showToastShort("分享失败，请重试！");
    }

    @Override
    public void onCancel(Platform platform, int i) {

    }
}
